<template>
  <j-modal
    :title="title"
    :width="1200"
    :visible="visible"
    switchFullscreen
    @ok="handleOk"
    :okButtonProps="{ class: { 'jee-hidden': disableSubmit } }"
    @cancel="close"
    cancelText="关闭"
  >
    <a-spin :spinning="confirmLoading">
      <a-tabs default-active-key="1" v-model="tabIndex" @change="onChange" style=" margin-left: 30px;">
        <a-tab-pane key="1" tab="漫入告警" v-if="isAdd || isEditMR">
          <div class="contentBox">
            <custom-table
              class="tableBox"
              ref="table1"
              rowKey="specialId"
              :showAlert="false"
              :showSelection="true"
              :loading="loading"
              :columns="columns1"
              :dataSource="pageData1"
              @selectedRow="onSelectedRow1"
              @change="onTableChange1"
            />
            <div class="qyBox">
              <span>漫入区域：</span>
              <a-select mode="multiple" placeholder="选择区域" v-model="dataForm1.regionIds" style="width:80%;">
                <a-select-option v-for="(item, i) in dictOptions" :key="i" :value="item.value">
                  {{ item.label }}
                </a-select-option>
              </a-select>
            </div>
          </div>
        </a-tab-pane>
        <a-tab-pane key="2" tab="漫出告警" v-if="isAdd || !isEditMR">
          <div class="contentBox">
            <custom-table
              class="tableBox"
              ref="table2"
              rowKey="specialId"
              :showAlert="false"
              :showSelection="true"
              :loading="loading"
              :columns="columns2"
              :dataSource="pageData2"
              @selectedRow="onSelectedRow2"
              @change="onTableChange2"
            />
            <div class="qyBox">
              <span>漫开区域：</span>
              <a-select mode="multiple" placeholder="选择区域" v-model="dataForm2.regionIds" style="width:80%;">
                <a-select-option v-for="(item, i) in dictOptions" :key="i" :value="item.value">
                  {{ item.label }}
                </a-select-option>
              </a-select>
            </div>
          </div>
        </a-tab-pane>
      </a-tabs>
    </a-spin>
    <template slot="footer">
      <a-button key="back" @click="close">取消</a-button>
      <a-button key="submit" type="primary" :loading="btnLoading" @click="handleOk">确定</a-button>
    </template>
  </j-modal>
</template>

<script>
import * as alarmApi from '@/api/xlgc/alarmCenter.js'
import * as areaEvent from '@/api/xlgc/areaEvent.js'
import CustomTable from '@/components/zxd/Table/CustomTable'
export default {
  name: 'RuleModal',
  components: {
    CustomTable
  },
  data() {
    return {
      title: '告警规则',
      visible: false,
      disableSubmit: false,
      btnLoading: false,
      dataForm1: {
        alarmType: '漫入',
        ids: [],
        regionIds: []
      },
      dataForm2: {
        alarmType: '漫出',
        ids: [],
        regionIds: []
      },
      dictOptions: [],
      selectedKeys: null,
      labelCol: { span: 5 },
      wrapperCol: { span: 18 },
      pageFilter1: {
        pageNo: 1,
        pageSize: 10
      },
      pageFilter2: {
        pageNo: 1,
        pageSize: 10
      },
      columns1: [
        {
          title: '序号',
          dataIndex: 'order',
          width: 60,
          align: 'center',
          customRender: (text, record, index) =>
            `${(this.pageFilter1.pageNo - 1) * this.pageFilter1.pageSize + (index + 1)}` // 序号分页后连续
        },
        {
          title: '告警目标',
          dataIndex: 'name',
          // width: 115,
          align: 'center'
        },
        {
          title: '联系方式',
          dataIndex: 'contactInformation',
          // width: 115,
          align: 'center'
        }
      ],
      columns2: [
        {
          title: '序号',
          dataIndex: 'order',
          width: 60,
          align: 'center',
          customRender: (text, record, index) =>
            `${(this.pageFilter2.pageNo - 1) * this.pageFilter2.pageSize + (index + 1)}` // 序号分页后连续
        },
        {
          title: '告警目标',
          dataIndex: 'name',
          // width: 115,
          align: 'center'
        },
        {
          title: '联系方式',
          dataIndex: 'contactInformation',
          // width: 115,
          align: 'center'
        }
      ],
      pageData1: {},
      pageData2: {},
      confirmLoading: false,
      loading: false,
      reloading: true,
      tabIndex: 1,
      isAdd: true,
      alarmType: '',
      id: ''
    }
  },
  computed: {
    isEditMR() {
      return !this.isAdd && this.alarmType == '漫入'
    }
  },
  methods: {
    // tabs切换
    onChange(e) {
      this.tabIndex = e
    },
    add() {
      this.isAdd = true
      this.alarmType = ''
      this.visible = true
      this.tabIndex = '1'
      this.$nextTick(() => {
        this.refreshTable1()
        this.getPageListByUnit()
      })
    },
    edit(record) {
      console.log(record)
      this.isAdd = false
      this.visible = true
      this.refreshTable1()
      this.getPageListByUnit()
      this.getDetail(record.id)
      this.id = record.id
      this.alarmType = record.alarmType
      if (this.alarmType == '漫入') {
        this.tabIndex = '1'
      } else {
        this.tabIndex = '2'
      }
    },
    getDetail(id) {
      alarmApi
        .alarmDetails(id)
        .then(res => {
          if (res.success) {
            let data = res.result.createAlarmVo
            if (this.alarmType == '漫入') {
              this.dataForm1.ids = data.ids
              this.dataForm1.regionIds = data.regionIds
              this.$refs.table1.selectedRowKeys = data.ids
            } else {
              this.dataForm2.ids = data.ids
              this.dataForm2.regionIds = data.regionIds
              this.$refs.table2.selectedRowKeys = data.ids
            }
          } else {
            this.$message.warn(res.message)
          }
        })
        .catch(e => {
          this.$message.warn('请求失败！')
        })
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    // 目标人群列表切换分页
    onTableChange1(pagination, pageFilter, sorter) {
      let keyMap = { currentPage: 'pageNo' }
      let paginations = Object.keys(pagination).reduce((newData, key) => {
        let newKey = keyMap[key] || key
        newData[newKey] = pagination[key]
        return newData
      }, {})
      this.pageFilter1 = Object.assign({}, this.pageFilter1, paginations)
      this.refreshTable1()
    },
    onTableChange2(pagination, pageFilter, sorter) {
      let keyMap = { currentPage: 'pageNo' }
      let paginations = Object.keys(pagination).reduce((newData, key) => {
        let newKey = keyMap[key] || key
        newData[newKey] = pagination[key]
        return newData
      }, {})
      this.pageFilter2 = Object.assign({}, this.pageFilter2, paginations)
      this.refreshTable2()
    },
    // 获取目标人群列表
    refreshTable1() {
      this.loading = true
      alarmApi
        .warningUser(this.pageFilter1)
        .then(res => {
          if (res.success) {
            this.pageData1 = res.result
            this.pageData2 = res.result
            this.loading = false
          } else {
            this.loading = false
            this.$message.warn(res.message)
          }
        })
        .catch(e => {
          this.loading = false
          this.$message.warn('请求失败！')
        })
    },
    refreshTable2() {
      this.loading = true
      alarmApi
        .warningUser(this.pageFilter2)
        .then(res => {
          if (res.success) {
            this.pageData2 = res.result
            this.loading = false
          } else {
            this.loading = false
            this.$message.warn(res.message)
          }
        })
        .catch(e => {
          this.loading = false
          this.$message.warn('请求失败！')
        })
    },
    // 获取区域列表
    getPageListByUnit() {
      areaEvent
        .getPageListByUnit({ regionType: 1, pageNo: 1, pageSize: 99999 }) // 告警区域regionType为1
        .then(res => {
          if (res.success) {
            let result = res.result.records
            this.dictOptions = result.map(v => {
              return {
                label: v.name,
                value: v.id
              }
            })
          } else {
            this.$message.warn(res.message)
          }
        })
        .catch(e => {
          this.$message.warn('请求失败！')
        })
    },
    // 选择目标人群列表
    onSelectedRow1(datas) {
      if (!datas || datas.length === 0) {
        this.dataForm1.ids = []
        return
      }
      let arr = []
      datas.forEach(item => {
        arr.push(Number(item.specialId))
      })
      this.dataForm1.ids = arr
      console.log(this.dataForm1)
    },
    onSelectedRow2(datas) {
      if (!datas || datas.length === 0) {
        this.dataForm2.ids = []
        return
      }
      let arr = []
      datas.forEach(item => {
        arr.push(Number(item.specialId))
      })
      this.dataForm2.ids = arr
      console.log(this.dataForm2)
    },
    // 提交保存
    handleOk() {
      // console.log(this.dataForm1.ids)
      // console.log(this.dataForm2.ids)
      if (this.dataForm1.ids.length <= 0 && this.dataForm2.ids.length <= 0) {
        this.$message.warning('目标人不能为空')
        return
      }
      if (this.dataForm1.regionIds.length <= 0 && this.dataForm2.regionIds.length <= 0) {
        this.$message.warning('区域不能为空')
        return
      }
      this.btnLoading = true
      let api
      if (this.isAdd) {
        let params = []
        if (this.dataForm1.ids.length <= 0) {
          params = [this.dataForm2]
        } else if (this.dataForm2.ids.length <= 0) {
          params = [this.dataForm1]
        } else {
          params = [this.dataForm1, this.dataForm2]
        }
        // 新增配置
        api = alarmApi.addAlarmRule(params)
      } else {
        let params = {}
        if (this.tabIndex == '1') {
          params = {
            configureId: this.id,
            createAlarmVo: {
              alarmType: this.alarmType,
              ids: this.dataForm1.ids,
              regionIds: this.dataForm1.regionIds
            }
          }
        } else {
          params = {
            configureId: this.id,
            createAlarmVo: {
              alarmType: this.alarmType,
              ids: this.dataForm2.ids,
              regionIds: this.dataForm2.regionIds
            }
          }
        }
        // 更新配置
        api = alarmApi.updateAlarmRule(params)
      }
      api
        .then(res => {
          if (res.success) {
            this.btnLoading = false
            let message = res.message ? res.message : '操作成功'
            this.$message.success(message)
            this.visible = false
            this.$emit('ok')
          } else {
            this.$message.warn(res.message)
          }
        })
        .catch(e => {
          this.$message.warn('操作失败！')
        })
    },

    /** 重新加载组件 */
    reload() {
      this.reloading = false
      this.$nextTick(() => (this.reloading = true))
    }
  }
}
</script>
<style lang="less" scoped>
.input {
  width: 90px;
  margin: 0 6px;
}
.select {
  width: 120px;
  margin: 0 10px;
}

.contentBox {
  display: flex;
  .tableBox {
    flex: 0 0 550px;
    border-right: 1px solid #e8e8e8;
    padding-left: 10px;
    padding-right: 10px;
  }
  .qyBox {
    flex: 0 0 500px;
    margin-left: 50px;
    // border-right: 1px solid #e8e8e8;
  }
  // &:nth-of-type(1) {
  //   flex: 0 0 550px;
  //   border-right: 1px solid #e8e8e8;
  //   padding-left: 10px;
  //   padding-right: 10px;
  // }
  // &:nth-of-type(2) {
  //   flex: 0 0 290px;
  //   // border-right: 1px solid #e8e8e8;
  // }
}

/deep/.ant-table-thead > tr > th,
/deep/.ant-table-tbody > tr > td {
  padding-left: 0;
  padding-right: 0;
}
/deep/.ant-table-thead > tr:first-child > th:first-child,
/deep/.ant-table-tbody > tr > td:first-child {
  padding-left: 10px;
}
/deep/.ant-modal-body {
  padding: 0;
}
</style>
